<?php
namespace Admin\Model;
use Admin\Model\BaseModel;

class CheckOrderModel extends BaseModel{
    
    /* 自动完成规则 */
    protected $_auto = array(
        array('create_time', 1, self::MODEL_INSERT, 'string'),
        array('update_time', 'time', self::MODEL_BOTH, 'function'),
    );
    
    /**
     * @todo    申请核销店铺列表
     */
    public function getApplyShopList(){
        
        $activity_id = (int)I('activity_id');
        $apply_start_time = (I('apply_start_time'))? strtotime(I('apply_start_time')) : 0 ;
        $apply_end_time = (I('apply_end_time'))? strtotime(I('apply_end_time')) : NOW_TIME ;
        if($activity_id == 0){
            return null;
        }
        $map['activity_id'] = $activity_id;
        $map['order_status'] = 5;
        if($apply_start_time > 0){
            $map['apply_time'] = array('between', array($apply_start_time, $apply_end_time));
        }
        return D('OrderShopView')->field('shop_id,shop_name,merchant_id,activity_id,order_status')->where($map)->group('shop_id')->select();
    }
    
    /**
     * @todo    质检订单更新
     */
    public function checkOrderUpdate(){

        $data['order_id'] = (int)I('post.order_id');
        $data['visit_type'] = (int)I('post.visit_type');
        $data['is_pass'] = (int)I('post.is_pass');
        $data['is_code'] = (int)I('post.is_code');
        $data['is_complain'] = (int)I('post.is_complain');
        $data['remark'] = strip_tags(I('post.remark'));
        $data['check_code'] = (int)I('post.check_code');
        $data['member_id'] = UID;
        if($data['order_id'] == 0){
            $this->error = '参数错误';
            return false;
        }
        
        $info = M('check_order')->where(array('order_id' => $data['order_id']))->getField('order_id');
        if($info > 0){
            $data['update_time'] = NOW_TIME;
            $order_id = $data['order_id'];
            unset($data['order_id']);
            $result = M('check_order')->where(array('order_id' => $order_id))->save($data);
        }else{
            $data['create_time'] = NOW_TIME;
            $result = M('check_order')->add($data);
        }
        return ($result)? true : false;
    }
    
    /**
     * @todo    获取订单的质检信息
     * @param   array $map
     * @param   string $field
     */
    public function getCheckOrderInfo($map, $field = true){
        if(empty($map)) return null;
        return M('check_order')->field($field)->where($map)->find();
    }
    
    public function getCheckOrderLogs($map, $field = true){
        if(empty($map)) return null;
        return M('check_order_log')->field($field)->where($map)->select();
    }
    
    /**
     * @todo 返回主键
     * @see \Think\Model::getPk()
     */
    public function getPk(){
        return 'check_order_id';
    }
}